package com.ruoyi.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
public class OpenStreetMapUtil {

    public static String getLocatin(String location){
        String locations = "";
        try {
            String apiKey = "2b03ec2181814627fe80e171e459990e";
            //String location = "116.397428,39.908585"; // 北京天安门广场的经纬度
            String urlString = "https://restapi.amap.com/v3/geocode/regeo?key=" + apiKey + "&location=" + location + "&extensions=all";
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/json");
            if (connection.getResponseCode() == 200) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                locations = response.toString();
                System.out.println(locations); // 打印响应结果
                log.info(locations);
            } else {
                System.out.println("Error: " + connection.getResponseCode());
                return connection.getResponseMessage();
            }
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return locations;
    }

}
